Skip to content

Conversation

@HA0N1
Copy link
Contributor

@HA0N1 HA0N1 commented Jan 10, 2025

변경 사항

  • 스웨거 문서화 추가
    • /api-docs 로 확인 가능

Summary by CodeRabbit

  • 새로운 기능

    • Swagger를 통한 API 문서화 기능 추가
    • 사용자 로그인, 로그아웃, 프로필 조회 엔드포인트 개선
    • 포스트 및 통계 관련 API 응답 구조 상세화
  • 버그 수정

    • 일부 DTO 및 응답 타입의 필수 속성 정의 개선
  • 문서화

    • 모든 주요 라우트에 대한 상세한 Swagger 문서 추가
    • API 엔드포인트의 요청/응답 스키마 명확화

@notion-workspace
Copy link

swagger 문서화

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 10, 2025

Walkthrough

이 풀 리퀘스트는 프로젝트의 API 문서화를 위해 Swagger를 통합하는 작업을 포함합니다. package.json에 Swagger 관련 의존성을 추가하고, app.ts에 Swagger UI 설정을 구현했습니다. 라우터와 DTO 파일들에 Swagger 문서화 주석을 추가하여 API 엔드포인트와 데이터 구조에 대한 상세한 문서를 제공합니다.

Changes

파일 변경 요약
package.json Swagger 관련 의존성 추가 (swagger-jsdoc, swagger-ui-express 및 해당 타입 정의)
src/app.ts Swagger UI 엔드포인트 /api-docs 추가
src/configs/swagger.config.ts Swagger 구성 옵션 생성
src/routes/* 다양한 라우트에 Swagger 문서화 주석 추가
src/types/dto/* API 요청 및 응답 DTO에 대한 Swagger 스키마 문서화
src/controllers/tracking.controller.ts, src/repositories/tracking.repository.ts, src/services/tracking.service.ts 생성자 포맷 조정
src/routes/user.router.ts /logout 엔드포인트의 인증 미들웨어 변경 및 Swagger 문서화 추가

Sequence Diagram

sequenceDiagram
    participant Client
    participant Server
    participant SwaggerUI
    participant APIEndpoints

    Client->>Server: Request /api-docs
    Server->>SwaggerUI: Serve Swagger Documentation
    SwaggerUI-->>Client: Display Interactive API Docs
    Client->>APIEndpoints: Make API Requests
    APIEndpoints-->>Client: Respond with Data
Loading

Possibly related PRs

Suggested labels

enhancement

Suggested reviewers

  • Nuung
  • BDlhj
  • six-standard

Poem

🐰 스웨거의 마법, API의 빛
문서화의 토끼 깡총깡총
엔드포인트들이 춤을 추네
코드는 명확해, 이해는 쉬워
개발의 즐거움 여기 있네! 🌈

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

🔭 Outside diff range comments (2)
src/types/dto/requests/getPostQuery.type.ts (1)

Line range hint 31-43: 생성자 매개변수가 선택적 속성과 일치하지 않습니다

DTO 클래스의 속성은 선택적(?)으로 정의되어 있지만, 생성자는 필수 매개변수로 정의되어 있습니다.

다음과 같이 수정하는 것을 추천드립니다:

-  constructor(start: string, end: string) {
+  constructor(start?: string, end?: string) {
    this.start = start;
    this.end = end;
  }
src/routes/post.router.ts (1)

Line range hint 1-2: 사용하지 않는 dotenv 임포트 제거 필요

dotenv 패키지를 임포트하고 있지만 실제로는 사용되지 않습니다.

다음과 같이 수정하세요:

import express, { Router } from 'express';
-import dotenv from 'dotenv';
import pool from '@/configs/db.config';

그리고 아래 라인도 제거하세요:

-dotenv.config();
🧹 Nitpick comments (9)
src/types/dto/requests/loginRequest.type.ts (1)

3-19: Swagger 문서에 예제 값과 상세한 설명이 필요합니다

API 문서의 가독성과 이해도를 높이기 위해 예제 값과 더 자세한 설명을 추가하는 것이 좋습니다.

다음과 같이 수정하는 것을 추천드립니다:

 /**
  * @swagger
  * components:
  *   schemas:
  *     LoginRequestDto:
  *       type: object
  *       required:
  *         - accessToken
  *         - refreshToken
  *       properties:
  *         accessToken:
  *          type: string
- *          description: accessToken
+ *          description: 사용자 인증을 위한 액세스 토큰
+ *          example: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
  *         refreshToken:
  *          type: string
- *          description: refreshToken
+ *          description: 액세스 토큰 갱신을 위한 리프레시 토큰
+ *          example: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
  */
src/types/dto/responses/baseResponse.type.ts (1)

19-22: 응답 데이터 타입이 구체적이지 않습니다

Swagger 문서에서 data 속성이 단순히 object 타입으로 정의되어 있어, 실제 응답 형식을 이해하기 어렵습니다.

다음과 같이 수정하는 것을 추천드립니다:

 *         data:
-*           type: object
+*           oneOf:
+*             - $ref: '#/components/schemas/PostResponseDto'
+*             - $ref: '#/components/schemas/UserResponseDto'
+*             - type: 'null'
 *           description: 응답 데이터 (구체적인 타입은 각 엔드포인트에서 정의)
 *           nullable: true
src/app.ts (1)

30-30: API 라우트 순서 검토 필요

Swagger UI 라우트가 API 라우트보다 먼저 정의되어 있습니다. 일반적으로 API 문서화 엔드포인트는 주요 API 라우트 이후에 정의하는 것이 좋습니다.

다음과 같이 라우트 순서를 변경하는 것을 고려해보세요:

-app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
app.use('/api', router);
+app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
src/types/dto/responses/loginResponse.type.ts (1)

3-51: 스키마 문서에 예시 추가 필요

Swagger 문서화가 잘 되어있지만, 각 스키마에 실제 사용 예시를 추가하면 API 사용자의 이해도를 높일 수 있습니다.

각 스키마에 다음과 같이 example을 추가해보세요:

 *       properties:
 *         thumbnail:
 *           type: string
 *           description: 프로필 이미지 URL
+*           example: "https://example.com/profile.jpg"
 *         id:
 *           type: integer
 *           description: 사용자 ID
+*           example: 12345
 *         username:
 *           type: string
 *           description: 사용자 이름
+*           example: "홍길동"
src/types/dto/requests/getAllPostsQuery.type.ts (1)

33-36: 커서 파라미터 설명 개선 필요

커서 파라미터에 대한 설명이 다소 부족합니다. 페이지네이션을 처음 사용하는 개발자를 위해 더 자세한 설명이 필요합니다.

다음과 같이 설명을 보완해보세요:

 *         cursor:
 *           type: string
-*           description: 다음 페이지 조회를 위한 커서값
+*           description: |
+*             다음 페이지 조회를 위한 커서값
+*             * 첫 페이지 조회 시에는 cursor를 전달하지 않음
+*             * 응답의 nextCursor 값을 다음 요청의 cursor로 사용
 *           nullable: true
+*           example: "2024-01-11T12:00:00.000Z"
src/routes/post.router.ts (1)

96-97: 오류 응답에 대한 스키마 참조 누락

401 응답에 대한 스키마 정의가 누락되어 있습니다.

다음과 같이 응답 스키마를 추가하세요:

 *       '401':
 *         description: Post조회 실패 / Unauthorized
+*         content:
+*           application/json:
+*             schema:
+*               $ref: '#/components/schemas/ErrorResponseDto'
src/types/dto/responses/postResponse.type.ts (2)

125-125: 문자열 끝에 불필요한 백틱 문자 제거

문서화 중 불필요한 백틱 문자가 발견되었습니다.

다음과 같이 수정하세요:

-           description: 게시물 제목`
+           description: 게시물 제목

Also applies to: 16-16


Line range hint 125-144: 응답 예시 추가 권장

Swagger 문서에 실제 응답 예시를 추가하면 API 사용자의 이해를 도울 수 있습니다.

다음과 같이 예시를 추가하세요:

 *               $ref: '#/components/schemas/PostResponseData'
+*         example:
+*           success: true
+*           message: "성공적으로 조회되었습니다"
+*           data:
+*             post:
+*               - date: "2024-01-25"
+*                 dailyViewCount: 100
+*                 dailyLikeCount: 50
package.json (1)

36-37: Swagger 관련 의존성 버전 범위 제한 권장

현재 캐럿(^) 범위를 사용하고 있어 예기치 않은 업데이트가 발생할 수 있습니다. 프로덕션 환경의 안정성을 위해 정확한 버전을 지정하는 것이 좋습니다.

다음과 같이 수정하세요:

-    "swagger-jsdoc": "^6.2.8",
-    "swagger-ui-express": "^5.0.1",
+    "swagger-jsdoc": "6.2.8",
+    "swagger-ui-express": "5.0.1",
-    "@types/swagger-jsdoc": "^6.0.4",
-    "@types/swagger-ui-express": "^4.1.7",
+    "@types/swagger-jsdoc": "6.0.4",
+    "@types/swagger-ui-express": "4.1.7",

Also applies to: 51-52

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c431e5b and 0b520b4.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (18)
  • package.json (2 hunks)
  • src/app.ts (2 hunks)
  • src/configs/swagger.config.ts (1 hunks)
  • src/controllers/tracking.controller.ts (1 hunks)
  • src/repositories/tracking.repository.ts (1 hunks)
  • src/routes/post.router.ts (1 hunks)
  • src/routes/tracking.router.ts (1 hunks)
  • src/routes/user.router.ts (1 hunks)
  • src/services/tracking.service.ts (1 hunks)
  • src/types/dto/requests/eventRequest.type.ts (1 hunks)
  • src/types/dto/requests/getAllPostsQuery.type.ts (2 hunks)
  • src/types/dto/requests/getPostQuery.type.ts (2 hunks)
  • src/types/dto/requests/loginRequest.type.ts (1 hunks)
  • src/types/dto/requests/stayTimeRequest.dto.ts (1 hunks)
  • src/types/dto/responses/baseResponse.type.ts (1 hunks)
  • src/types/dto/responses/emptyReponse.type.ts (1 hunks)
  • src/types/dto/responses/loginResponse.type.ts (1 hunks)
  • src/types/dto/responses/postResponse.type.ts (4 hunks)
✅ Files skipped from review due to trivial changes (6)
  • src/services/tracking.service.ts
  • src/types/dto/requests/stayTimeRequest.dto.ts
  • src/controllers/tracking.controller.ts
  • src/repositories/tracking.repository.ts
  • src/types/dto/responses/emptyReponse.type.ts
  • src/types/dto/requests/eventRequest.type.ts

Comment on lines +13 to +30
/**
* @swagger
* components:
* schemas:
* GetPostQueryDto:
* type: object
* properties:
* start:
* type: string
* format: date
* description: 조회 시작 날짜
* nullable: true
* end:
* type: string
* format: date
* description: 조회 종료 날짜
* nullable: true
*/
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

DTO 속성 타입과 Swagger 문서가 일치하지 않습니다

Swagger 문서에는 nullable: true로 정의되어 있지만, 실제 DTO에서는 string 타입으로 정의되어 있습니다.

다음과 같이 수정하는 것을 추천드립니다:

 *         start:
 *           type: string
 *           format: date
 *           description: 조회 시작 날짜
-*           nullable: true
+*           example: "2024-01-01"
 *         end:
 *           type: string
 *           format: date
 *           description: 조회 종료 날짜
-*           nullable: true
+*           example: "2024-12-31"
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
/**
* @swagger
* components:
* schemas:
* GetPostQueryDto:
* type: object
* properties:
* start:
* type: string
* format: date
* description: 조회 시작 날짜
* nullable: true
* end:
* type: string
* format: date
* description: 조회 종료 날짜
* nullable: true
*/
/**
* @swagger
* components:
* schemas:
* GetPostQueryDto:
* type: object
* properties:
* start:
* type: string
* format: date
* description: 조회 시작 날짜
* example: "2024-01-01"
* end:
* type: string
* format: date
* description: 조회 종료 날짜
* example: "2024-12-31"
*/

Copy link
Member

@six-standard six-standard left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

전체적으로 문서화가 잘 되서 좋네요~
다만 린팅 규칙이 바뀌신건지 중간 중간 띄어쓰기 제거만 된 파일들이 보이던데, 이 부분들은 왜 이럴련지 궁금합니다!

@HA0N1 HA0N1 added the enhancement New feature or request label Jan 13, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
src/configs/swagger.config.ts (1)

1-8: API 문서의 메타데이터를 보강해주세요

API 문서의 기본 정보를 더 상세하게 제공하면 좋겠습니다. 다음 항목들의 추가를 고려해주세요:

  • contact: 개발팀 연락처 정보
  • license: 라이선스 정보
  • termsOfService: 서비스 이용 약관 링크
    info: {
      title: 'V.D Project API',
      version: '1.0.0',
      description: '모든 API는 로그인 후 진행이 가능합니다.',
+     contact: {
+       name: 'V.D Project Team',
+       email: 'team@example.com'
+     },
+     license: {
+       name: 'MIT',
+       url: 'https://opensource.org/licenses/MIT'
+     }
    },
src/routes/user.router.ts (1)

30-47: 응답 코드 설명 개선 필요

현재 응답 코드 설명이 불충분합니다:

  • 400: "DTO 검증 실패"는 어떤 검증이 실패했는지 구체적으로 명시해야 합니다.
  • 401: 여러 실패 케이스가 한 줄에 나열되어 있어 명확하지 않습니다.
  • 500: 구체적인 오류 상황과 해결 방법이 명시되어 있지 않습니다.

각 응답 코드별로 구체적인 설명과 예시를 추가하는 것을 권장합니다. 예시:

 *       '400':
-*         description: DTO 검증 실패
+*         description: |
+*           요청 데이터 검증 실패:
+*           - 필수 필드 누락
+*           - 잘못된 데이터 형식
+*         content:
+*           application/json:
+*             example:
+*               success: false
+*               message: "유효하지 않은 요청 데이터"
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0b520b4 and 52b549f.

📒 Files selected for processing (5)
  • src/configs/swagger.config.ts (1 hunks)
  • src/controllers/user.controller.ts (1 hunks)
  • src/routes/tracking.router.ts (1 hunks)
  • src/routes/user.router.ts (1 hunks)
  • src/types/dto/requests/eventRequest.type.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/types/dto/requests/eventRequest.type.ts
  • src/routes/tracking.router.ts
🔇 Additional comments (5)
src/configs/swagger.config.ts (3)

9-13: 서버 URL을 환경 변수로 관리해야 합니다

현재 서버 URL이 하드코딩되어 있어 개발/스테이징/프로덕션 환경에서 문제가 될 수 있습니다.


14-29: ⚠️ Potential issue

보안 스키마 구성을 개선해주세요

현재 구현에는 몇 가지 개선이 필요합니다:

  1. JWT 토큰의 경우 일반적으로 Bearer 인증 방식을 사용합니다.
  2. 설명에는 토큰을 헤더, 쿠키, 요청 본문으로 전달할 수 있다고 되어있지만, 설정은 헤더만 지원합니다.

다음과 같이 수정하는 것을 추천드립니다:

    components: {
      securitySchemes: {
        AccessTokenAuth: {
-         type: 'apiKey',
+         type: 'http',
+         scheme: 'bearer',
+         bearerFormat: 'JWT',
          description: 'API 인증을 위한 액세스 토큰입니다. 헤더, 쿠키 또는 요청 본문을 통해 전달할 수 있습니다.',
-         name: 'access_token',
-         in: 'header',
        },
        RefreshTokenAuth: {
-         type: 'apiKey',
+         type: 'http',
+         scheme: 'bearer',
+         bearerFormat: 'JWT',
          description: '토큰 갱신을 위한 리프레시 토큰입니다. 헤더, 쿠키 또는 요청 본문을 통해 전달할 수 있습니다.',
-         name: 'refresh_token',
-         in: 'header',
        },
      },
    },

Likely invalid or redundant comment.


37-37: API 경로 패턴이 모든 필요한 파일을 포함하는지 확인해주세요

현재 설정된 패턴이 모든 API 정의와 타입을 포함하는지 확인이 필요합니다.

다음 스크립트로 Swagger 문서화 관련 파일들을 확인할 수 있습니다:

✅ Verification successful

현재 Swagger 설정의 경로 패턴이 정확합니다

모든 라우트 파일과 타입 정의 파일이 현재 패턴으로 올바르게 포함되어 있습니다:

  • ./src/routes/*.ts: 모든 라우터 파일 포함 (4개 파일)
  • ./src/types/**/*.ts: 중첩된 모든 타입 파일 포함 (21개 파일)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# API 라우트 파일 확인
echo "라우트 파일 목록:"
fd -e ts . src/routes

echo "\n타입 정의 파일 목록:"
fd -e ts . src/types

echo "\nSwagger 데코레이터 사용 현황:"
rg -l "@swagger|@ApiProperty" src/

Length of output: 1592

src/routes/user.router.ts (2)

24-25: 로그인 요청 바디가 필수가 아닌 것으로 명시됨

Swagger 문서에서 requestBodyrequired: false로 설정되어 있습니다. 로그인에는 사용자 정보가 필수적입니다.


66-66: 인증 미들웨어 변경에 대한 검토 필요

authMiddleware.login에서 authMiddleware.verify로의 변경이 적절한지 확인이 필요합니다.

다음 스크립트를 실행하여 두 미들웨어의 차이점을 확인하세요:

✅ Verification successful

미들웨어 변경이 적절함을 확인했습니다

로그아웃 엔드포인트에서 authMiddleware.verify의 사용이 적절합니다. 이유는 다음과 같습니다:

  • 로그아웃은 이미 등록된 사용자를 대상으로 하므로 Velog API 확인이 불필요합니다
  • verify 미들웨어는 토큰 검증과 DB에서의 사용자 존재 여부만 확인하여 더 효율적입니다
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# 미들웨어 구현 비교
ast-grep --pattern 'export const authMiddleware = {
  $$$
  login($$$) {
    $$$
  },
  verify($$$) {
    $$$
  }
  $$$
}'

Length of output: 124


Script:

#!/bin/bash
# Find potential auth middleware files
fd middleware

# Search for auth-related files
fd auth

# Search for login and verify function implementations
rg -A 5 "login.*=.*async.*\(|verify.*=.*async.*\(" --type ts

Length of output: 842


Script:

#!/bin/bash
# View auth middleware implementation
cat src/middlewares/auth.middleware.ts

Length of output: 3951

Comment on lines +30 to +35
security: [
{
AccessTokenAuth: [],
RefreshTokenAuth: [],
},
],
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

보안 요구사항을 엔드포인트 특성에 맞게 조정해주세요

현재 모든 엔드포인트에 AccessTokenAuthRefreshTokenAuth가 모두 필요하도록 설정되어 있습니다. 일반적으로:

  • 대부분의 엔드포인트는 액세스 토큰만 필요합니다
  • 리프레시 토큰은 토큰 갱신 엔드포인트에서만 사용됩니다

다음과 같이 수정하는 것을 추천드립니다:

    security: [
      {
        AccessTokenAuth: [],
-       RefreshTokenAuth: [],
      },
    ],

그리고 토큰 갱신 엔드포인트에서만 다음과 같이 개별적으로 리프레시 토큰을 요구하도록 설정하세요:

// 토큰 갱신 라우트에서
/**
 * @swagger
 * /auth/refresh:
 *   post:
 *     security:
 *       - RefreshTokenAuth: []
 */

Comment on lines +18 to +20
baseOptions.domain = process.env.ALLOWED_ORIGINS;
} else {
baseOptions.domain = 'localhost';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

🛠️ Refactor suggestion

쿠키 도메인 설정이 잘못되었습니다

process.env.ALLOWED_ORIGINS를 쿠키 도메인으로 직접 사용하는 것은 다음과 같은 이유로 작동하지 않습니다:

  1. ALLOWED_ORIGINS는 "http://localhost,http://localhost:3000,https://myapp.com" 형식의 전체 URL 목록을 포함합니다.
  2. 쿠키 도메인은 프로토콜이나 포트 없이 순수한 도메인 이름만 허용합니다.

수정 제안:

if (isProd) {
  baseOptions.sameSite = 'lax';
  baseOptions.domain = process.env.COOKIE_DOMAIN;
} else {
  baseOptions.domain = process.env.COOKIE_DOMAIN || 'localhost';
}
🔗 Analysis chain

쿠키 도메인 설정 검토 필요

다음과 같은 잠재적인 문제가 있습니다:

  1. process.env.ALLOWED_ORIGINS는 일반적으로 CORS를 위한 origin 목록을 포함하므로, 쿠키 도메인으로 사용하기에 적절하지 않을 수 있습니다.
  2. 개발 환경에서 'localhost' 하드코딩은 다른 개발 환경(예: Docker, 원격 개발 서버 등)에서 문제를 일으킬 수 있습니다.

다음 스크립트를 실행하여 ALLOWED_ORIGINS 환경 변수의 형식을 확인하세요:

다음과 같이 수정하는 것을 권장합니다:

if (isProd) {
  baseOptions.sameSite = 'lax';
-  baseOptions.domain = process.env.ALLOWED_ORIGINS;
+  baseOptions.domain = process.env.COOKIE_DOMAIN;
} else {
-  baseOptions.domain = 'localhost';
+  baseOptions.domain = process.env.COOKIE_DOMAIN || 'localhost';
}
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# ALLOWED_ORIGINS 환경 변수가 쿠키 도메인으로 적절한지 확인
rg "ALLOWED_ORIGINS.*=.*" .env* || echo "No ALLOWED_ORIGINS found in .env files"

Length of output: 114


Script:

#!/bin/bash
# Check if ALLOWED_ORIGINS is transformed before use
rg -A 3 "ALLOWED_ORIGINS" --type ts

Length of output: 607

@Nuung Nuung merged commit dd13247 into main Jan 14, 2025
1 check passed
@Nuung Nuung deleted the feature/swagger-docs branch January 14, 2025 12:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants